package com.gec.zhs.aspect;

import com.gec.zhs.annotation.ZhsLogin;
import com.gec.zhs.entity.constants.Constants;
import com.gec.zhs.entity.dto.TokenUserInfoDto;
import com.gec.zhs.entity.enums.ResponseCodeEnum;
import com.gec.zhs.exception.BusinessException;
import com.gec.zhs.redis.RedisUtils;
import com.gec.zhs.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author zhs
 * @version 1.0
 * @date 2025-01-20
 * @description AOP切面进行登陆校验
 */

@Component
@Aspect
@Slf4j
public class ZhsAspect {

    @Autowired
    private RedisUtils redisUtils;


    @Before("@annotation(com.gec.zhs.annotation.ZhsLogin)")
    public void getInterceptorAndCheckLogin(JoinPoint point) {
        //通过反射获取interceptor
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        ZhsLogin zhsInterceptor = method.getAnnotation(ZhsLogin.class);
        if (null == zhsInterceptor) {
            return;
        }
        /**
         * 校验登录
         */
        if (zhsInterceptor.checkLogin()) {
            checkLogin();
        }
    }

    //校验登录
    private void checkLogin() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Constants.TOKEN_WEB);
        if (StringTools.isEmpty(token)) {
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }
        TokenUserInfoDto tokenUserInfoDto = (TokenUserInfoDto) redisUtils.get(Constants.REDIS_KEY_TOKEN_WEB + token);
        if (tokenUserInfoDto == null) {
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }
    }

}
